package br.com.unipar.cursoweb.util;

import java.io.IOException;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.application.FacesMessage.Severity;
import javax.faces.context.FacesContext;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 *
 * @author Thiago
 */
@Component
@Scope("request")
public class FacesUtils implements Serializable {

    private static final long serialVersionUID = 26L;
    private final FacesContext facesContext;
    private static final Logger LOGGER = Logger.getLogger(FacesUtils.class);

    @Autowired
    public FacesUtils(FacesContext facesContext) {
        this.facesContext = facesContext;
    }

    public void mensagem(String clientId, String mensagem, Severity severity) {
        FacesContext context = FacesContext.getCurrentInstance();
        FacesMessage message = new FacesMessage(severity, mensagem, null);
        context.addMessage(clientId, message);
    }

    public void redirect(String page) {
        try {
            FacesContext.getCurrentInstance().getExternalContext().redirect(page);
        } catch (IOException ex) {
            LOGGER.error(ex.getMessage());
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro ao redicionar página, tente novamente!", null));
        }
    }
}
